﻿using Growatt.Component.Cls;
using Growatt.ShinebusServiceUploadPack.Service.FeishuHelper;
using Growatt.ShinebusServiceUploadPack.Service.OSS.Model;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public class OssProductListFeishu : BaseHttpClient
{

    public OssProductListFeishu(string baseID, string tablesID, string accessToken, IHttpClientFactory httpClientFactory, ILogger<OssProductListFeishu> logger, string urlUploadFileFieshuUrl) : base(httpClientFactory, urlUploadFileFieshuUrl)
    {
        this.baseID = baseID;
        this.tablesID = tablesID;
        this.accessToken = accessToken;
        _logger = logger;
    }

    /// <summary>
    /// 查询飞书产品列表，并返回记录的ID
    /// </summary>
    /// <param name="viewId"></param>
    /// <returns></returns>
    public async Task<List<Growatt.ShinebusServiceUploadPack.Service.OSS.Model.DeviceDataListItem>> SearchProductRecordsRecordAsync(string urlUploadFileFieshuUrl)
    {
        var apiHelper = new FeishuAPIHelper();

        accessToken = await apiHelper.GetTenantAccessToken();
        UpdateIDs(urlUploadFileFieshuUrl);
        // 定义请求地址
        string url = $"{BaseAddress}bitable/v1/apps/{baseID}/tables/{tablesID}/records/search?page_size=499";

        // 创建请求体
        var requestBody = new { view_id = ViewId };
        string jsonBody = JsonConvert.SerializeObject(requestBody);
        var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

        // 发送 POST 请求
        string responseContent = await SendPostRequestAsync(url, content, _logger, accessToken);

        if (!string.IsNullOrEmpty(responseContent))
        {
            var rootObject = JsonConvert.DeserializeObject<FeishuDeviceRootTobject>(responseContent);
            return rootObject.data.items.ToList();
        }

        return new List<Growatt.ShinebusServiceUploadPack.Service.OSS.Model.DeviceDataListItem>();
    }

  

    // 注入ILogger
    private readonly ILogger<OssProductListFeishu> _logger;

    public OssProductListFeishu(IHttpClientFactory httpClientFactory, ILogger<OssProductListFeishu> logger, string urlUploadFileFieshuUrl) : base(httpClientFactory, urlUploadFileFieshuUrl)
    {
        _logger = logger;
    }
}
